package com.xn.app.muying.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.adpter.BabyStudyListAdpter;
import com.xn.app.muying.bean.BabyStudyListBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/11/16.
 */
public class BabyStudyListActivity extends BaseActivity implements HttpUtil.OnGetDataListener, AdapterView.OnItemClickListener ,MyListView.IXListViewListener{
    private Handler handler = new Handler();
    private BabyStudyListAdpter babyStudyListAdpter;
    private ArrayList<BabyStudyListBean> list = new ArrayList<>();
    private TextView activity_doctor_list_title;
    //数据显示列表
    private MyListView listview=null;
    //返回键
    private ImageView activity_doctor_list_back;
    //加载框
    AlertDialog dialog;
    //记录标题
    private String title=null;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 10;

    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_babystudylist);
        //加载并缓存图片
        imageLoader = MyImageLoader.getImageLoader(this);
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();

        listview = (MyListView) findViewById(R.id.activity_babystudylist_listview);
        activity_doctor_list_back= (ImageView) findViewById(R.id.activity_doctor_list_back);
        activity_doctor_list_title= (TextView) findViewById(R.id.activity_doctor_list_title);
        title=getIntent().getStringExtra("name");
        activity_doctor_list_title.setText(title);
        babyStudyListAdpter = new BabyStudyListAdpter(this,imageLoader,options);
        listview.setAdapter(babyStudyListAdpter);
        listview.setOnItemClickListener(this);
        activity_doctor_list_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(this)) {
            dialog = new MyAlertDialog().ShowDialog(BabyStudyListActivity.this, R.layout.dialog_loading);
            dialog.setCancelable(true);
            HttpUtil.getData(APIMethod.BabyStudyList(getIntent().getStringExtra("id"), currentPage, number), handler, this);
        } else {
            ToastUtil.showToast(this, R.string.no_network_hint);
        }
    }

    @Override
    public void onJsonData(String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            totalCount =Integer.parseInt(jsonObject.optString("totalCount"));
            JSONArray items = jsonObject.getJSONArray("items");
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String title = object.optString("title");
                String pictureUrl = object.optString("pictureUrl");
                String shortDescription = object.optString("shortDescription");
                String categoryId = object.optString("categoryId");
                String id = object.optString("id");
                BabyStudyListBean babyStudyListBean = new BabyStudyListBean();
                    babyStudyListBean.setTitle(title);
                    babyStudyListBean.setPictureUrl(pictureUrl);
                    babyStudyListBean.setShortDescription(shortDescription);
                    babyStudyListBean.setCategoryId(categoryId);
                    babyStudyListBean.setId(id);
                    list.add(babyStudyListBean);
            }
            listview.setPullLoadEnable(true);
            listview.setXListViewListener(BabyStudyListActivity.this, totalCount, currentPage, number);
            onLoad();
            babyStudyListAdpter.getData(list);
            dialog.dismiss();
            if(listview.getVisibility()==View.GONE){
                listview.setVisibility(ListView.VISIBLE);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "文章查看");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent intent = new Intent();
        intent.putExtra("type", 1);
        intent.putExtra("id", list.get(i).getId());
        intent.putExtra("name", title);
        intent.putExtra("title", list.get(i).getTitle());
        intent.putExtra("content", list.get(i ).getShortDescription());
        intent.putExtra("pic", list.get(i).getPictureUrl());
        intent.setClass(BabyStudyListActivity.this, EducationDetailsActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onLoadMore() {
        if (totalCount > currentPage * number) {
            currentPage = currentPage + 1;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(AppConstant.THREAD_SLEEP);
                        //下载数据
                        HttpUtil.getData(APIMethod.BabyStudyList(getIntent().getStringExtra("id"), currentPage, number), handler, BabyStudyListActivity.this);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        } else {
            onLoad();
        }
    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        listview.stopLoadMore();
    }
}
